package com.situ.web.controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Student;
import com.situ.web.util.JDBCUtil;

// 访问这个servlet的名字
// http://localhost:8080/Java202007Web/studentSelect
@WebServlet("/studentSelect")
public class StudentSelectServlet extends HttpServlet{

	// 访问servlet时候默认访问service方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentServlet.service()");
		
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		ArrayList<Student> list = new ArrayList<Student>();
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT `id`,`name`,`age`,`gender` FROM `student`";
			statement = connection.prepareStatement(sql);
			resultSet = statement.executeQuery();
			System.out.println(statement);
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				Student student = new Student(id, name, age, gender);
				list.add(student);
			}
			for (Student student : list) {
				System.out.println(student);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		
		// 把数据放到request里面，就相当于一块内存区域
		req.setAttribute("list", list);
		// 转发（跳转）到student_list.jsp页面进行展示
		req.getRequestDispatcher("student_list.jsp").forward(req, resp);
	}
}
